class_name MapGenerator

#region 属性
var map_manager:MapManager
#endregion
#region 字段
#endregion
#region 信号
#endregion

#region 基类方法
#endregion
#region 公共方法
func generate_map(map_info:MapInfo) -> BaseMap:
	var room_rand_seed = GameManager.get_grng().grng_randi()
	GameManager.get_grng().grng_fixed_seed(room_rand_seed)
	var room_dict:Dictionary[int,BaseRoom] = {}
	var map:BaseMap = load(map_info.map_script).new(map_manager,map_info,room_dict)
	map_manager.add_child(map)
	for idx in map_info.map_room_info_dict.keys():
		var map_room_info:MapRoomInfo = map_info.map_room_info_dict[idx]
		var room_id = map_room_info.room_ids.pick_random()
		var room_info = map_manager.get_room_info_by_id(room_id)
		if not room_info:
			continue
		var row = idx / map_info.map_shape.y
		var col = idx % map_info.map_shape.y
		var room_pos:Vector2 = Vector2(col * (map_info.room_boundary_size.x + map_info.room_spacing.x),row * (map_info.room_boundary_size.y + map_info.room_spacing.y))
		var room_args = {
			Map = map,
			Pos = room_pos,
			Index = idx,
		}
		var room:BaseRoom = map_manager.room_generator.generate_room(room_info,room_args)
		room_dict[idx] = room
	# 生成所有路
	for room:BaseRoom in map.get_rooms_by_type():
		# 只在房间的上和右方向生成路，防止重复
		var road_tile_map_layer:TileMapLayer = room.find_child("Layers").find_child("Road")
		var wall_tile_map_layer:TileMapLayer = room.find_child("Layers").find_child("Wall")
		# TODO 假设路宽2个单位
		var road_width = 2
		var road_length = map_info.room_spacing.y / 16
		var row = room.room_idx / map_info.map_shape.y
		var col = room.room_idx % map_info.map_shape.y
		var room_pos:Vector2 = Vector2(col * (map_info.room_boundary_size.x + map_info.room_spacing.x),row * (map_info.room_boundary_size.y + map_info.room_spacing.y))
		var c = road_tile_map_layer.local_to_map(road_tile_map_layer.to_local(room_pos + map_info.room_boundary_size/2))
		var room_width = map_info.room_boundary_size.x / 16
		var room_height = map_info.room_boundary_size.y / 16
		var top_left_pos = Vector2i(c.x - 1 + room_width/2,c.y - road_width/2)
		var bottom_right_pos = Vector2i(c.x + 1 + room_width/2+road_length,c.y - road_width/2+road_width-1)
		RoadCreater.paint_road(road_tile_map_layer,RoadCreater.RoadType.Horizontal,map_info.road_info_horizontal,top_left_pos,bottom_right_pos,func(coords):
				wall_tile_map_layer.set_cell(coords)
				)
	GameManager.get_grng().grng_randomize()
	return map
#endregion
#region 私有方法
#endregion
#region 生命周期函数
func _init(map_manager:MapManager) -> void:
	self.map_manager = map_manager
#endregion
